package myQueue;

import java.util.Deque;
import java.util.LinkedList;

class Ticket {

    public int timeRequiredToBuy(int[] tickets, int k) {
        // 构造FIFO双端队列，尾进头出
        Deque<TicketBuyer> buyerDeque = new LinkedList<>();
        for (int i = 0; i < tickets.length; i++) {
            TicketBuyer buyer = new TicketBuyer();
            buyer.index = i;
            buyer.ticketCnt = tickets[i];
            buyerDeque.addLast(buyer);
        }

        // 统计耗时
        int cost = 0;
        while (!buyerDeque.isEmpty()) {
            // 头出
            TicketBuyer buyer = buyerDeque.pollFirst();
            // 一个人一次只能买一张票
            buyer.ticketCnt -= 1;
            // 每个人买票都需要用掉恰好1秒
            cost++;
            if (buyer.ticketCnt > 0) {
                // 如果需要购买更多票，他必须走到队尾重新排队
                buyerDeque.addLast(buyer);
            } else {
                if (buyer.index == k) {
                    // 返回位于位置k的人完成买票需要的时间
                    return cost;
                }
            }
        }

        return cost;
    }

    // 买票者信息
    private class TicketBuyer {
        // 索引位
        private Integer index;
        // 要购买票数
        private Integer ticketCnt;
    }

}

public class BuyTicket {
    public static void main(String[] args) {
        int[] ticket = {2, 3, 2};
        int pos = 2;
        Ticket ticket1 = new Ticket();
        int timeReq = ticket1.timeRequiredToBuy(ticket, pos);
        System.out.println(timeReq);
    }
}



